package com.order.consumer;

import com.alibaba.fastjson.JSONObject;
import com.order.entity.DispatchEntity;
import com.order.repository.DispatchRosipotory;
import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;

import java.io.IOException;
import java.util.Optional;

@Slf4j
@Component
public class DispatchConsumer {
    @Autowired
    private DispatchRosipotory dispatchRosipotory;

    @RabbitListener(queues = "order_dic_queue")
    public void dispatchConsumer(Message message, Channel channel) throws IOException {
        // 1.获取消息
        String msg = new String(message.getBody());
        // 2.转换json
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String orderId = jsonObject.getString("orderId");
        // 查看该订单是否已经派单，如果有派单，则返回
        Optional<DispatchEntity> entity = dispatchRosipotory.findByOrderId(orderId);
        if(entity.isPresent()) { // orderId 要唯一性
            return;
        }
        // 计算分配的快递员id
        DispatchEntity dispatchEntity = new DispatchEntity(orderId, 1234L);
        // 3.插入我们的数据库
        DispatchEntity result = dispatchRosipotory.save(dispatchEntity);
        if (!ObjectUtils.isEmpty(result)) {
            log.info("分配的快递员成功，消息删除");
            // 手动将该消息删除
            // 手动ack 删除该消息
            channel.basicAck(message.getMessageProperties().getDeliveryTag(), false);
        }

    }
}